<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use think\Exception;
use think\Request;
use think\Db;

/**
 * 促销/优惠券
 */
class Promotion extends Base
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'coupon';
        $this->defaultWhere = ['is_del'=>0];
        $type    = get_coupon_type();
        $purpose = get_coupon_purpose();
        $productCategoryMdl = model('Productcategory');
        $category = $productCategoryMdl->where('status',1)->select();
        $this->assign('type',$type);
        $this->assign('purpose',$purpose);
        $this->assign('category',$category);
    }

    public function index(){
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            // 排序条件
            $order = '';

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            if($this->defaultOrder){
                $order = $this->defaultOrder;
            }

            $data = $model->where($where)->limit($start, $length)->order($order)->select();
            $count = $model->where($where)->count();

            foreach($data as $k => $v)
            {
                $time = time();
                $end_time = strtotime($v['end_time']);
                if ($end_time < $time){
                    $v['statustime'] = '已过期';
                }else{
                    $v['statustime'] = '未过期';
                }
                if ($v['number'] == 0){
                    $v['number'] = '--';
                }
                $v['coupon_type'] = show_coupon_type($v['coupon_type']);
                $v['coupon_purpose'] = show_coupon_purpose($v['coupon_purpose']);
                $v['key'] = $k + 1;
            }
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return self::show($this->indexView, [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * Add
     */
    public function add(Request $request){
        return parent::add($request);
    }

    /**
     * Add Post
     */
    public function addPost(Request $request, $redirect = ''){
        $param = $request->param();
        $error = $this->checkparam($param);
        if($error['code'] != 0){
            return $this->error($error['msg']);
        }
        $model = model($this->model);
        if ($request->isPost()){
            if (!empty($param['cash_amount'])){
                $data['cash_amount'] = $param['cash_amount'] * 100;
            }
            if (!empty($param['discount_strength'])){
                $data['discount_strength'] = $param['discount_strength'] * 10;
            }
            if(!empty($param['threshold'])){
                $data['threshold'] = $param['threshold'] * 100;
            }
            $data['name'] = $param['name'];
            $data['coupon_type'] = $param['coupon_type'];
            $data['coupon_purpose'] = $param['coupon_purpose'];
            $data['start_time'] = $param['start_time'];
            $data['end_time'] = $param['end_time'] . ' 23:59:59';
            $data['number'] = $param['number'];
            // Insert data
            Db::startTrans();
            $result = $model->insertGetId($data);
            if (!empty($param['category_id'])){
                $categoryMdl = model('CouponProductCategory');
                $category_id = implode(',',$param['category_id']);
                $item = [
                    'id' => Helper::getUUID(),
                    'coupon_id' => $result,
                    'category_id' => $category_id
                ];
                $saveCategory = $categoryMdl->save($item);

                if (!$saveCategory){
                    Db::rollback();
                    return $this->error($model->getError());
                }
            }elseif (!empty($param['product_id'])){
                $categoryMdl = model('CouponProduct');
                $item = [
                    'id' => Helper::getUUID(),
                    'coupon_id' => $result,
                    'product_id' => $param['product_id']
                ];
                $saveCategory = $categoryMdl->save($item);
                if (!$saveCategory){
                    Db::rollback();
                    return $this->error($model->getError());
                }
            }
            $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';

            if($result !== false) {
                // Query执行后的操作
                $model->_after_update($data);

                // 写入日志
                Common::adminLog($request, $logInfo);
                Db::commit();
                return $this->success('添加成功！', 'admin/promotion/index');
            } else {
                Db::rollback();
                return $this->error($model->getError());
            }
        }else{
            Db::rollback();
            $this->error('提交方式错误!');
        }
    }

    private function checkparam($param){
        if(!in_array($param['coupon_type'],[1,2,3,4,5,6])){
            $error['code'] = '400021';
            $error['msg'] = '优惠券类型错误';
            return $error;
        }
        if(empty($param['name'])){
            $error['code'] = '400022';
            $error['msg'] = '优惠券名称必填';
            return $error;
        }
        if(!in_array($param['coupon_purpose'],[1,2,3])){
            $error['code'] = '400023';
            $error['msg'] = '优惠券用途错误';
            return $error;
        }
        if($param['coupon_purpose'] != 1){
            if(!preg_match("/^[1-9][0-9]*$/",$param['number'])){
                $error['code'] = '400024';
                $error['msg'] = '优惠券数量有误';
                return $error;
            }
        }
        if(empty($param['start_time'])){
            $error['code'] = '400025';
            $error['msg'] = '开始时间必填';
            return $error;
        }
        if(empty($param['end_time'])){
            $error['code'] = '400026';
            $error['msg'] = '结束时间必填';
            return $error;
        }
        if($param['coupon_type'] == 1 || $param['coupon_type'] == 2 || $param['coupon_type'] == 3){
            if(!$this->checkcash_amount($param['threshold'])){
                $error['code'] = '400027';
                $error['msg'] = '请填写使用门槛金额';
                return $error;
            }
        }
        if($param['coupon_type'] == 1 || $param['coupon_type'] == 2 || $param['coupon_type'] == 3){
            if(!$this->checkcash_amount($param['cash_amount'])){
                $error['code'] = '400028';
                $error['msg'] = '抵现金额不合法';
                return $error;
            }
        }
        if($param['coupon_type'] == 4 || $param['coupon_type'] == 5 || $param['coupon_type'] == 6){
            if(!preg_match('/^((0\.[1-9]{1})|(([1-9]{1})(\.\d{1})?))$/',$param['discount_strength'])){
                $error['code'] = '400029';
                $error['msg'] = '折扣错误';
                return $error;
            }
        }
        if($param['coupon_type'] == 3 || $param['coupon_type'] == 6){
            if(empty($param['product_id'])){
                $error['code'] = '400030';
                $error['msg'] = '必须选择商品';
                return $error;
            }
        }
        if($param['coupon_type'] == 2 || $param['coupon_type'] == 5){
            if(empty($param['category_id'])){
                $error['code'] = '400031';
                $error['msg'] = '必须选择分类';
                return $error;
            }
        }

        if(!empty($param['cash_amount']) && !empty($param['threshold'])){
            if((float)$param['cash_amount'] >= (float)$param['threshold']){

                $error['code'] = '400032';
                $error['msg'] = '使用门槛金额必须大于抵现金额';
                return $error;
            }
        }
        $error['code'] = 0;
        $error['msg'] = '';
        return $error;
    }

    private function checkcash_amount($value){
        $match = "/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/";
        if($value < 0){
            return false;
        }
        if(preg_match($match,$value)){
            return true;
        }
        return false;
    }

    /**
     * Edit
     */
    public function edit(Request $request){

        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        $categoryMdl = model('CouponProductCategory');
        $productMdl = model('CouponProduct');

        $categor = $categoryMdl->where('coupon_id',$id)->field('category_id')->find();
        if ($categor){
            $categor = explode(',',$categor['category_id']);
        }else{
            $categor = [0];
        }
        $product = $productMdl->alias('a')->where('a.coupon_id',$id)
            ->join('product p','a.product_id = p.id')
            ->field('p.id,p.name')
            ->find();
        if (!$product){
            $product['name']='请选择';
            $product['id']='';
        }
        $this->assign('product',$product);
        $this->assign('categors',$categor);
        $info['start_time'] = substr($info['start_time'],0,10);
        $info['end_time'] = substr($info['end_time'],0,10);
        if (!empty($info['cash_amount'])) {
            $info['cash_amount'] = $info['cash_amount'] / 100;
        }
        if (!empty($info['threshold'])) {
            $info['threshold'] = $info['threshold'] / 100;
        }
        if (!empty($info['discount_strength'])) {
            $info['discount_strength'] = $info['discount_strength'] / 10;
        }
        return $this->show($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Edit Post
     */
    public function editPost(Request $request, $redirect = ''){
        $data = $request->param();
        $error = $this->checkparam($data);
        if($error['code'] != 0){
            return $this->error($error['msg']);
        }
        $model = model($this->model);
        if ($request->isPost()){
            if (empty($data['id'])){
                $this->error('参数异常');
            }
            $data['end_time'] = $data['end_time'] . ' 23:59:59';
            if (!empty($data['cash_amount'])){
                $data['cash_amount'] = $data['cash_amount'] * 100;
            }else{
                unset($data['cash_amount']);
            }
            if (empty($data['discount_strength'])){
                unset($data['discount_strength']);
            }else{
                $data['discount_strength'] = $data['discount_strength']*10;
            }
            if (empty($data['threshold'])){
                unset($data['threshold']);
            }else{
                $data['threshold'] = $data['threshold']*100;
            }

            // Insert data
            Db::startTrans();
            try{
                $model->allowField(true)->save($data, ['id' => $data['id']]);
                $logInfo = $this->admin->name . '编辑了一条' . lang($this->model) . '数据。';
                $Coupon = \app\admin\model\Coupon::where('id',$data['id'])->find();
                if($Coupon->coupon_type == 2 || $Coupon->coupon_type == 5){
                    $categoryMdl = model('CouponProductCategory')->where('coupon_id',$data['id'])->find();
                    if ($categoryMdl) {
                        if (!empty($data['category_id'])){
                            $category_id = implode(',',$data['category_id']);
                            $categoryMdl->category_id = $category_id;
                            $categoryMdl->save();
                        }else{
                            $categoryMdl->delete();
                        }
                    }
                }
                if($Coupon->coupon_type == 3 || $Coupon->coupon_type == 6){
                    $categoryMdl = model('CouponProduct')->where('coupon_id',$data['id'])->find();
                    if ($categoryMdl) {
                        if(!empty($data['product_id'])){
                            $categoryMdl->product_id = $data['product_id'];
                            $categoryMdl->save();
                        }else{
                            $categoryMdl->delete();
                        }
                    }
                }
                Db::commit();
                Common::adminLog($request, $logInfo);
                return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }else{
            $this->error('提交方式错误!');
        }
    }

    //选择优惠商品
    public function get_product()
    {
        return $this->fetch();
    }

    public function get_product_list()
    {
        $productMdl = model('product');
        $fields = 'a.id,a.name,a.bar_code,a.store_count,a.price,a.status,p.name as typeName';
        $data = $productMdl->alias('a')
            ->where('a.status',1)
            ->join('product_category p','a.category_id = p.id')
            ->field($fields)
            ->select();
        $result = [
            'code' => '0',
            'msg' => '请求成功',
            'data' => $data,
        ];
        return json($result);
    }

    //删除优惠券
    public function delete()
    {
        $model = model($this->model);
        $categoryMdl = model('CouponProductCategory');
        $productMdl = model('CouponProduct');

        $request = $this->request;
        $id = $request->param('id');

        //判断优惠券是否被使用
        $useInfo = $this->isUsed($id);
        if ($useInfo['code'] != 1){
            $this->error($useInfo['msg']);
        }
        // 删除一条
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }
        if ($info['status'] == 1){
            return $this->error('启用状态无法删除');
        }
        $result = $model->where('id', $id)->update(['is_del'=>1]);
        $categoryMdl->where('coupon_id', $id)->delete();
        $productMdl->where('coupon_id', $id)->delete();

        if($result !== false){
            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
            Common::adminLog($request, $logInfo);
        }

        if($result !== false){
            if(strtolower($request->controller()) != strtolower($this->model)){
                return $this->success('删除成功！', 'admin/' . strtolower($request->controller()) . '/index');
            }else{
                return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
            }
        }else{
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();
            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /*
     * 优惠券是否被使用
     * */
    protected function isUsed($id){
        if(!$id){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 判断会员等级是否使用该卷
        $coupon_ids = db('member_level')->where('status',1)->field('coupon_ids')->select();
        foreach($coupon_ids as $v)
        {
            $coupon_id = explode(',',$v['coupon_ids']);
            foreach($coupon_id as $val)
            {
                if ($id == $val){
                    return ['code' => 0, 'msg' => '该优惠券被会员等级使用,请先删除会员等级中该卷使用!'];
                }
            }
        }
        //判断优惠券是否在积分商城中
        $integral_product = db('integral_product')->where('coupon_id',$id)->field('coupon_id')->find();
        if ($integral_product){
            return ['code' => 0, 'msg' => '该优惠券被积分商城使用,请先删除积分商城中该卷使用!'];
        }
        return ['code' => 1, 'msg' => ''];
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }
        if(isset($param['coupon_purpose']) && $param['coupon_purpose']){
            $where['coupon_purpose'] = $param['coupon_purpose'];
        }
        if(isset($param['coupon_type']) && $param['coupon_type']){
            $where['coupon_type'] = $param['coupon_type'];
        }
        if(isset($param['time']) && $param['time']){
            $time = date('Y-m-d H:i:s',time());
            if ($param['time'] == 2){
                $where['end_time'] = ['lt',$time];
            }else{
                $where['end_time'] = ['gt',$time];
            }
        }

        return $where;
    }


    private function show($template, $data = []) {

        return $this->view->fetch($template, $data);
    }
}